package TCPEcho;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TCPEchoCline {
    private Socket socket = null;

    public TCPEchoCline(String severIp,int severPort) throws IOException {
        socket = new Socket(severIp,severPort);
    }

    public void start() throws IOException {
        System.out.println("客户端启动！");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scannerConsole = new Scanner(System.in);
            Scanner scannerNetwork = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while(true){
                //1、从控制台读取输入的字符串
                System.out.print("->");
                if(!scannerConsole.hasNext()){
                    break;
                }
                String request = scannerConsole.next();
                //2、把请求发给服务器
                writer.println(request);
                writer.flush();
                //3、从服务器读取响应
                String response = scannerNetwork.next();
                System.out.println(response);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoCline tcpEchoCline = new TCPEchoCline("127.0.0.1",7675);
        tcpEchoCline.start();
    }
}
